package tree.medium;

import tree.TreeNode;

import java.util.*;

/**
 * 103. 二叉树的锯齿形层序遍历
 */
public class zigzagLevelOrder {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        LinkedList<TreeNode> stake = new LinkedList<>();
        stake.offer(root);
        int flag = 0;
        while (!stake.isEmpty()) {
            int size = stake.size();
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = stake.poll();
                if (flag % 2 == 0) {
                    list.offerLast(node.val);
                } else {
                    list.offerFirst(node.val);
                }
                if (node.left != null) {
                    stake.offer(node.left);
                }
                if (node.right != null) {
                    stake.offer(node.right);
                }
            }
            res.add(list);
            flag++;
        }
        return res;
    }
}
